package org.share.comm.os;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 命令行执行工具类
 * 
 * @author hhm
 *
 */
public class CommandUtils {

	private static final Logger logger = LoggerFactory.getLogger(CommandUtils.class);

	/**
	 * 执行命令行命令
	 * 
	 * @param cmd
	 */
	public static void executeCommand(String cmd) {
		executeCommand(cmd,new CommandOutputCallback(){

			@Override
			public void deal(String line) {
				
			}
			
		});
	}

	/**
	 * 执行命令行命令，并对输出行回调处理
	 * 
	 * @param cmd
	 * @param callback
	 */
	public static void executeCommand(String cmd, CommandOutputCallback callback) {
		try {
			logger.info("executeCommand() cmd : " + cmd);
			Process proc = Runtime.getRuntime().exec(cmd);
			InputStream stdis = proc.getInputStream();
			InputStream erris = proc.getErrorStream();
			
			//线程处理错误输出流
			ErrorInputStreamThread.start(erris);
			
			// 用一个读输出流类去读
			InputStreamReader stdisr = new InputStreamReader(stdis);
			// 用缓冲器读行
			BufferedReader stdbr = new BufferedReader(stdisr);
			// 直到读完为止
			String stdLine = null;
			do {
				stdLine = stdbr.readLine();
				if (stdLine != null) {
					logger.debug(stdLine);
					callback.deal(stdLine);
				}
			} while (stdLine != null);
			stdbr.close();
			proc.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 命令行输出回调接口
	 * 
	 * @author hhm
	 *
	 */
	public interface CommandOutputCallback {
		/**
		 * 输出行回调方法
		 * 
		 * @param line
		 */
		void deal(String line);
	}

	private static class ErrorInputStreamThread implements Runnable {

		InputStream erris = null;

		public ErrorInputStreamThread(InputStream errorInputStream) {
			erris = errorInputStream;
		}
		
		public static void start(InputStream errorInputStream){
			new Thread(new ErrorInputStreamThread(errorInputStream)).start();
		}

		@Override
		public void run() {
			try {
				// 用一个读输出流类去读
				InputStreamReader errisr = new InputStreamReader(erris);
				// 用缓冲器读行
				BufferedReader errbr = new BufferedReader(errisr);
				// 直到读完为止
				String errLine = null;
				do {
					errLine = errbr.readLine();
					logger.warn(errLine);
				} while (errLine != null);
				erris.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}
}
